<template>
  <div>
    <!-- 添加参数 -->
    <el-button @click="addVisible = true" :disabled="btStatus" size="small" type="primary">
      {{btnTitle}}
    </el-button>
    <!-- 表格 -->
    <el-table height="350" :data="dataList" border stripe>
      <!-- 折叠行 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-tag :key="i" v-for="(tag,i) in scope.row.attr_vals" closable :disable-transitions="false" @close="handleClose(i,scope.row)">
            {{tag}}
          </el-tag>
          <el-input class="input-new-tag" style="margin-left:10px" v-if="scope.row.inputVisible" v-model.trim="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
          </el-input>
          <el-button style="margin-left:10px" v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
        </template>

      </el-table-column>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column min-width="200" :label="labelName" prop="attr_name"></el-table-column>
      <!-- 操作 -->
      <el-table-column min-width="200" label="操作">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" size="small" type="primary" @click="addFrom.attr_name=scope.row.attr_name;addVisible = true;addFrom.id = scope.row.attr_id;postAttributes">编辑</el-button>
          <el-button icon="el-icon-delete" size="small" type="danger" @click="deleteAttributes(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加修改操作对话框 -->
    <el-dialog @closed="closeAddVisible" :title="(addFrom.id===''?'添加':'修改')+labelName" :visible.sync="addVisible" width="50%">
      <el-form :model="addFrom" :rules="addrules" ref="addFormRef" label-width="80px">
        <el-form-item :label="labelName" prop="attr_name">
          <el-input v-model="addFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="postAttributes">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'dynamic',
  props: {
    // 按钮状态
    btStatus: {
      type: Boolean,
      default: true
    },
    // 按钮名称
    btnTitle: {
      type: String,
      default: '添加参数'
    },
    // 商品id
    cateId: {
      type: Number,
      require: true
    },
    // 获取数据时参数
    sel: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dataList: [],
      // 添加的对话框
      addVisible: false,

      addFrom: {
        id: '',
        attr_name: '',
        attr_sel: this.sel,
        attr_vals: ''
      },
      addrules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 获取数据
    async getattributes() {
      const { data: res } = await this.$api.goods.getAttributesApi(this.cateId, this.sel)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.inputVisible = false
        item.inputValue = ''
        if (item.attr_vals === '') {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(' ')
        }
      })
      this.dataList = res.data
    },
    // splitString(data) {
    //   if (data.attr_vals === '') return ''
    //   return data.attr_vals.split(' ')
    // },
    closeAddVisible() {
      this.$refs.addFormRef.resetFields()
      this.addFrom = {
        id: '',
        attr_name: '',
        attr_sel: this.sel,
        attr_vals: ''
      }
    },
    // 提交，修改
    postAttributes() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        // 修改逻辑
        if (this.addFrom.id !== '') {
          // 提交逻辑
          const { data: res } = await this.$api.goods.putAttributesApi(this.cateId, this.addFrom.id, {
            attr_name: this.addFrom.attr_name,
            attr_sel: this.addFrom.attr_sel
          })
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success('修改成功')
        } else {
          // 提交逻辑
          const { data: res } = await this.$api.goods.postAttributesApi(this.cateId, this.addFrom)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success('添加成功')
        }

        this.getattributes()
        this.addVisible = false
      })
    },
    async deleteAttributes(row) {
      const confirResult = await this.$confirm('此操作将永久删除该条数据，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirResult === 'confirm') {
        const { data: res } = await this.$api.goods.deleteAttributesApi(row.cat_id, row.attr_id)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('删除成功')
        this.getattributes()
      }
    },
    // 展示输入框
    showInput(row) {
      row.inputVisible = true
      // 在页面dom渲染完再执行
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 失去焦点，或回车
    async handleInputConfirm(row) {
      if (row.inputValue === '') return (row.inputVisible = false)
      // 定义一个新数组提交
      const attrVals = [...row.attr_vals, row.inputValue]
      // 提交逻辑
      const { data: res } = await this.$api.goods.putAttributesApi(row.cat_id, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        // 因为提交需要改成字符串
        attr_vals: attrVals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      row.attr_vals.push(row.inputValue)
      this.$message.success('添加成功')
      // 切换为按钮
      row.inputVisible = false
      // 清空值
      row.inputValue = ''
    },
    // 删除标签
    async handleClose(idx, row) {
      const attrVals = row.attr_vals.concat()
      attrVals.splice(idx, 1)
      // 提交逻辑
      const { data: res } = await this.$api.goods.putAttributesApi(row.cat_id, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        // 因为提交需要改成字符串
        attr_vals: attrVals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      row.attr_vals.splice(idx, 1)
      this.$message.success('删除成功')
    }
  },
  computed: {
    // 属性名称
    labelName() {
      if (this.sel === 'only') return '属性名称'
      return '参数名称'
    }
  },
  watch: {
    // 如果商品id发生改变那么说明切换了种类那么就获取新数据
    cateId(newVal, oldVal) {
      if (newVal !== 0) {
        this.getattributes()
      } else {
        this.dataList = []
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
}
</style>
